package com.zp.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zp.common.constant.ProductConstant;
import com.zp.mall.product.dao.AttrAttrgroupRelationDao;
import com.zp.mall.product.dao.AttrGroupDao;
import com.zp.mall.product.dao.CategoryDao;
import com.zp.mall.product.entity.AttrAttrgroupRelationEntity;
import com.zp.mall.product.entity.AttrGroupEntity;
import com.zp.mall.product.entity.CategoryEntity;
import com.zp.mall.product.vo.AttrEditResponseVo;
import com.zp.mall.product.vo.AttrRequestVo;
import com.zp.mall.product.vo.AttrResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zp.common.utils.PageUtils;
import com.zp.common.utils.Query;

import com.zp.mall.product.dao.AttrDao;
import com.zp.mall.product.entity.AttrEntity;
import com.zp.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.w3c.dom.Attr;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page (
                new Query<AttrEntity> ().getPage (params),
                new QueryWrapper<AttrEntity> ()
        );

        return new PageUtils (page);
    }

    /**
     * 保存属性
     * 还需要保存属性与属性分组的关联
     *
     * @param attr
     */
    @Override
    @Transactional
    public void saveAttr(AttrRequestVo attr) {
        AttrEntity attrEntity = new AttrEntity ();
        BeanUtils.copyProperties (attr, attrEntity);
        this.save (attrEntity); //保存属性
        //基本属性有属性分组  销售属性没有
        if (attr.getAttrType () == ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode ()){
            //保存属性-属性分组
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity ();
            attrAttrgroupRelationEntity.setAttrId (attrEntity.getAttrId ());
            attrAttrgroupRelationEntity.setAttrGroupId (attr.getAttrGroupId ());
            attrAttrgroupRelationDao.insert (attrAttrgroupRelationEntity);
        }
    }

    /**
     * 查询属性（规格参数）根据类别和其它条件
     *
     * @param params
     * @param catelogId
     * @param attrTypePath
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrTypePath) {
        Integer attrType = attrTypePath.equalsIgnoreCase ("base") ? ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode () : ProductConstant.AttrTypeEnum.ATTR_TYPE_SALE.getCode ();
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity> ().eq ("attr_type", attrType);

        if (catelogId != 0) {
            queryWrapper.eq ("catelog_id", catelogId);
        }

        String key = (String) params.get ("key");
        if (!StringUtils.isEmpty (key)) {
            queryWrapper.and ((wrapper) -> {
                wrapper.eq ("attr_id", key).or ().like ("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page (
                new Query<AttrEntity> ().getPage (params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils (page);
        List<AttrEntity> records = page.getRecords ();
        List<AttrResponseVo> attrResponseVos = records.stream ().map (attrEntity -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo ();
            BeanUtils.copyProperties (attrEntity, attrResponseVo);

            //设置attrResponseVo 分类名称 属性分组名称   大数据量的表尽量不要去连表查询
            if (attrType == ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode ()) {  //只有基本属性有属性分组  销售属性没有
                // 获取 分类名称 属性分组名称
                AttrAttrgroupRelationEntity attrId = attrAttrgroupRelationDao.selectOne (new QueryWrapper<AttrAttrgroupRelationEntity> ().eq ("attr_id", attrEntity.getAttrId ()));
                if (attrId != null && attrId.getAttrGroupId () != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById (attrId.getAttrGroupId ());
                    attrResponseVo.setGroupName (attrGroupEntity.getAttrGroupName ());
                }
            }


            List<String> categoryNamePath = new ArrayList<> ();  //保存三级分类路径
            getPathName (attrEntity.getCatelogId (), categoryNamePath);
            Collections.reverse (categoryNamePath);
            String namePath = String.join ("/", categoryNamePath); //用 / 连接字符串  例：手机/数码/手机
            attrResponseVo.setCatelogName (namePath);

            return attrResponseVo;
        }).collect (Collectors.toList ());
        pageUtils.setList (attrResponseVos);
        return pageUtils;
    }

    @Override
    public AttrEditResponseVo getDetailAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById (attrId);
        AttrEditResponseVo attrEditResponseVo = new AttrEditResponseVo ();
        BeanUtils.copyProperties (attrEntity, attrEditResponseVo);
        if (attrEntity.getAttrType () == ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode ()) { //只有基本属性有属性分组  销售属性没有
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne (new QueryWrapper<AttrAttrgroupRelationEntity> ().eq ("attr_id", attrEntity.getAttrId ()));
            if (attrAttrgroupRelationEntity != null) {
                attrEditResponseVo.setAttrGroupId (attrAttrgroupRelationEntity.getAttrGroupId ());
            }
        }
        return attrEditResponseVo;
    }

    @Transactional
    @Override
    public void removeAttrByIds(Long[] attrIds) {
        if (attrIds != null && attrIds.length > 0){
            AttrEntity attrEntity = this.getById (attrIds[0]);  //没删除前获取一个属性  看是什么类型的

            this.removeByIds (Arrays.asList (attrIds));

            //判断删除的是不是基本属性  是的话就要删除  属性-属性分组关联表 相关的数据
            if (attrEntity.getAttrType () == ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode ()) {
                //删除中间表 属性-属性分组关联表
                attrAttrgroupRelationDao.delete (new QueryWrapper<AttrAttrgroupRelationEntity> ().in ("attr_id", Arrays.asList (attrIds)));
            }
        }
    }

    @Transactional
    @Override
    public void updateAttr(AttrRequestVo attr) {
        AttrEntity attrEntity = new AttrEntity ();
        BeanUtils.copyProperties (attr, attrEntity);
        this.updateById (attrEntity);

        //销售属性没有属性分组  基本属性有
        if (attr.getAttrType () == ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode ()) {
            //修改 属性-属性分组关联表  根据属性ID修改分组ID
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity ();
            attrAttrgroupRelationEntity.setAttrGroupId (attr.getAttrGroupId ());
            attrAttrgroupRelationEntity.setAttrId (attr.getAttrId ());

            Integer count = attrAttrgroupRelationDao.selectCount (new QueryWrapper<AttrAttrgroupRelationEntity> ().eq ("attr_id", attr.getAttrId ()));

            if (count > 0) {
                //先删除没有对应属性分组ID的数据 属性-属性分组关联表
                attrAttrgroupRelationDao.delete (new QueryWrapper<AttrAttrgroupRelationEntity> ().eq ("attr_id", attr.getAttrId ()));
            }
            if (attrAttrgroupRelationEntity.getAttrId () != null && attrAttrgroupRelationEntity.getAttrGroupId () != null) {
                //新增 属性-属性分组关联表   此时属性没有对应的属性分组
                attrAttrgroupRelationDao.insert (attrAttrgroupRelationEntity);
            }
        }


    }

    /**
     * 根据属性分组ID获取基本属性
     * @param attrgroupId   属性分组ID
     * @return
     */
    @Override
    public List<AttrEntity> getAttrsByAttrgroupId(Long attrgroupId) {
        // 根据属性分组ID获取属性-属性分组中间表数据
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationDao.selectList (new QueryWrapper<AttrAttrgroupRelationEntity> ().eq ("attr_group_id", attrgroupId));
        // 获取属性ID的集合
        List<Long> attrIdList = attrgroupRelationEntities.stream ().map (attrAttrgroupRelationEntity -> {
            return attrAttrgroupRelationEntity.getAttrId ();
        }).collect (Collectors.toList ());
        //获取属性
        Collection<AttrEntity> attrEntities = this.listByIds (attrIdList);
        return (List<AttrEntity>) attrEntities;
    }

    private void getPathName(Long catelogId, List<String> categoryNamePath) {
        CategoryEntity categoryEntity = categoryDao.selectById (catelogId);
        if (categoryEntity != null) {
            categoryNamePath.add (categoryEntity.getName ());
            getPathName (categoryEntity.getParentCid (), categoryNamePath);
        }
    }

}